package ren.steve.common.utils;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @Author: CIS-T-13 Liu GuoJia
 * @Description: JWT Token 生成工具
 * @Date: Created in 2024/1/30 13:20
 */

public class JwtHelper {
  // 设置过期时间
  private static long tokenExpiration = 24 * 60 * 60 * 1000;
  // 加密秘钥
  private static String tokenSignKey = "123456";

  // 生成 Token
  public static String createToken(String userId, String code, String email, String phone) {
    return Jwts.builder()
      // 设置分组
      .setSubject("AUTH-USER")
      // 设置过期时间
      .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
      // 加密Token包含哪些有效载荷
      .claim("id", userId).claim("code", code).claim("email", email).claim("phone", phone)
      // 根据秘钥进行加密处理
      .signWith(SignatureAlgorithm.HS512, tokenSignKey)
      // 压缩生成的编码
      .compressWith(CompressionCodecs.GZIP)
      .compact();
  }
  // 根据 Token 获取 UserID
  public static String getUserId (String token) {
    try {
      if (StringUtils.isEmpty(token)) {
        return null;
      }
      Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
      Claims claims = claimsJws.getBody();
      String userId = (String) claims.get("id" );
      return userId;
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
  // 根据 Token 获取 Username
  public static String getUserInfo (String token, String infoType) {
    try {
      if (StringUtils.isEmpty(token)) {
        return "";
      }
      Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
      Claims claims = claimsJws.getBody();
      return (String) claims.get(infoType);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  // 删除 Token
  public static void removeToken (String token) {
    // jwt token 无需删除,客户端丢掉即可
  }
  // 测试方法
  public static void main(String[] args) {
    String token1 = JwtHelper.createToken("1", "U0044096", "guojia.liu@lingyue-digital.com", "18301110525");
    String token = "eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAABXKQQ6CMBCF4bvMGkinBausdGGCW6UHqLSpYwolYBON8e4Ou5f_fV9Y8x1aOJm-K83tfIUC_HuGFrXQSkstRQF59cvFsVLbO1qKvENOT7JVpHyMNIVP9qWjQC8bqyGNDIfkPDvT17U47DjMjzRtBfdKIKJoZAO_P_rGOh6BAAAA.gH2pHumbEk7tgsoFp71H0ksOk9HCWRBkdZS2vouD0_6h0rs2pyLWL1cmJQ7RMEyKLSDuE_CudbwqXS485QhQYQ";
    System.out.println(JwtHelper.getUserInfo(token, "id"));
    System.out.println(JwtHelper.getUserInfo(token, "phone"));
    System.out.println(JwtHelper.getUserInfo(token, "code"));
    System.out.println(JwtHelper.getUserInfo(token, "email"));
  }

}
